'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.
/**
 * @fileoverview 战斗相关接口
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var _ = require('lodash');
var soldierAttr = require('./soldierAttr');
var buildAttr = require('./buildAttr');
var dataApi = require('../dataApi');
var soldierModel = require('../../models/soldierModel');
var buildModel = require('../../models/buildModel');
var roleModel = require('../../models/roleModel');
var bagModel = require('../../models/bagModel');
var skillModel = require('../../models/skillModel');
var techModel = require('../../models/techModel');
var unionGroupModel = require('../../models/unionGroupModel');
var buildConf = require('../../config/buildConf');
var buildTypeUtil = require('../../util/buildTypeUtil');
var buildType = require('../../consts/buildType');
var heroConf = require('../../config/heroConf');
var constantUtil = require('../../util/constantUtil');
var heroAttr = require('./heroAttr');
var equipPropertyService = require('../../services/equipPropertyService');
var unionTechService = require('../../services/unionTechService');
var unionTechType = require('../../consts/unionTechType');
var techType = require('../../consts/techType');
var techConf = require('../../config/techConf');
var techService = require('../../services/techService');
var playerManager = require('../../libs/playerManager.js');
var buildService = require('../../services/buildService.js');
var pvpService = require('../../services/pvpService.js');

exports.getData = function (role_id, callback) {
    var build_model;
    var soldier_model;
    var role_model;
    var bag_model;
    var skill_model;
    var tech_model;
    var harry_res;
    var union_model = null;

    var player_manager = new playerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.getModel(
                    ['build', 'soldier', 'role', 'bag', 'skill', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var union_id = player_manager.role.union_id;
                if (union_id !== 0) {
                    unionGroupModel.getById(union_id, function (err, model) {
                        union_model = model;
                        cb();
                    });
                } else {
                    cb();
                }
            },
            function (cb) {
                build_model = player_manager.build;
                soldier_model = player_manager.soldier;
                role_model = player_manager.role;
                bag_model = player_manager.bag;
                skill_model = player_manager.skill;
                tech_model = player_manager.tech;

                harry_res = pvpService.getHarryRes(role_model, build_model, tech_model, union_model);

                cb();
            }
        ],
        function (err) {
            if (!!err) {
                return callback(err);
            }

            callback(null, {
                name: role_model.getName(),
                lv: role_model.getLv(),
                total_gold: harry_res.gold,
                total_food: harry_res.food,
                total_exp: heroConf.getHeroPvpExp(role_model.getLv()),
                hero: _getHeroAttr(role_model, bag_model, skill_model, build_model),
                road_list: _getRoadList(build_model),
                build_list: _getBuildList(build_model, tech_model, union_model),
                soldier_list: _getSoldierList(build_model, soldier_model, bag_model, tech_model),
                union_tech_eff: unionTechService.getUnionTechForSoldierEff(union_model)
            });
        }
    );
};

/**
 * 获取英雄数据
 */
var _getHeroAttr = function (role_model, bag_model, skill_model, build_model) {
    return heroAttr.getAttr(role_model, bag_model, skill_model, build_model);
};

/**
 * 获取道路数据
 * @param  {[type]} build_model [description]
 * @return {[type]}             [description]
 */
var _getRoadList = function (build_model) {
    return build_model.getRoadList();
};

/**
 * 获取建筑数据
 * @param  {[type]} build_model [description]
 * @return {[type]}             [description]
 */
var _getBuildList = function (build_model, tech_model, union_model) {
    // 计算总的损失比例值
    var lost_proportion_total = 0;
    var def_build_list = build_model.getDefBuildList();
    def_build_list.push(build_model.getBuildByType(buildType.WALL));

    _.each(def_build_list, function (build) {
        if (build.getLv() <= 0) {
            return;
        }
        var build_type = buildTypeUtil.getBuildType(build.getBuildId());
        var building_type_conf = dataApi.building_type.findById(build_type);
        if (!!building_type_conf) {
            lost_proportion_total += building_type_conf.lost_proportion;
        }
    });

    // 计算建筑列表
    var build_list = [];
    _.each(def_build_list, function (build) {
        var build_id = build.getBuildId();
        var build_type = buildTypeUtil.getBuildType(build_id);
        var build_cell = build.getCell();
        var build_lv = build.getLv();
        var build_star = build.getStar();

        // 建筑类型配置
        var building_type_conf = dataApi.building_type.findById(build_type);

        // 建筑的金币比例
        var build_per = 0;
        if (!!building_type_conf) {
            build_per = building_type_conf.lost_proportion / lost_proportion_total * 100;
        }

        // 获取建筑的配置
        var build_conf = buildConf.getBuildLvConf(build_type, build_lv);
        if (!build_conf) {
            return;
        }

        var build_item = {
            build_id: build_id,
            cell: build_cell,
            per: build_per,
            star: build_star,
            attr: buildAttr.getAttr(build_type, build_lv)
        };

        var original_wall_hp = 0;
        if (build_type == buildType.WALL) {
            // 取出科技加成之前的城墙血量，用于计算联盟科技加成的城墙血量
            original_wall_hp = build_item.attr.hp;
        }

        // 附加科技效果
        _getWithTechEff(build_type, build_item, tech_model);

        // 附加星级加成
        buildService.getBuildStarEff(build_item);

        if (build_type == buildType.WALL) {
            build_item.soldier_list = build.getSelectSoldier();
            if (!!union_model) {
                _getWithUnionTechEff(build_item, original_wall_hp, union_model);
            }
        }

        build_list.push(build_item);
    });
    return build_list;
};

/**
 * 获取士兵数据
 * @param  {[type]} soldier_list [description]
 * @return {[type]}              [description]
 */
var _getSoldierList = function (build_model, soldier_model, bag_model, tech_model) {
    var soldier_list = [];
    var soldier_type_list = [];

    _.each(build_model.getEcoBuildList(), function (build) {
        var build_type = buildTypeUtil.getBuildType(build.build_id);
        if (build_type == buildType.WALL) {
            _.each(build.soldier_list, function (batch_info) {
                soldier_type_list = _.union(soldier_type_list, batch_info.sub_soldier_list);
            });
        }
    });

    _.each(soldier_type_list, function (soldier_type) {
        var soldier_item = soldier_model.getSoldier(soldier_type);
        if (!!soldier_item) {
            soldier_item = soldierAttr.getAttr(
                soldier_type,
                soldier_item.getLv(),
                soldier_item.getStar(),
                soldier_item.talent
            );

            techService.getSoldierAttrWithTechEff(soldier_item, tech_model);

            soldier_list.push(soldier_item);
        }
    });

    return soldier_list;
};

/**
 * 附加科技效果
 * @param  {[type]} soldier_list [description]
 * @return {[type]}              [description]
 */
var _getWithTechEff = function (build_type, build_item, tech_model) {
    var build_to_techid = {
        '104': [13, 14, 15, 16, 74],
        '105': [17, 18, 19, 20, 75],
        '106': [21, 22, 23, 24, 76],
        '107': [25, 26, 27, 28, 77],
        '108': [29, 30, 31, 32, 78],
        '109': [33, 34, 35, 36, 79],
        '110': [37, 38, 39, 40, 80],
        '111': [41, 42, 43, 44, 45, 81],
        '112': [46],
        '113': [47],
        '101': [48],
        '212': [54, 55]
    };

    var tech_list = build_to_techid[build_type] || null;
    if (!tech_list) {
        return;
    }

    _.each(tech_list, function (tech_type) {
        var tech_eff_val = tech_model.getEffByTechType(tech_type);
        techService.addBuildTechEff(build_item, tech_type, tech_eff_val);
    });
};

/**
 * 附加联盟科技效果
 * @param  {[type]} soldier_list [description]
 * @return {[type]}              [description]
 */
var _getWithUnionTechEff = function (build_item, original_wall_hp, union_model) {
    var attr = build_item.attr;
    var tech_add_hp = unionTechService.getUnionTechEff(union_model, unionTechType.UNION_TECH_101);
    var tech_add_atk = unionTechService.getUnionTechEff(union_model, unionTechType.UNION_TECH_102);
    attr.hp += Math.ceil(original_wall_hp * tech_add_hp / 100);
    attr.min_atk += Math.ceil(attr.min_atk * tech_add_atk / 100);
    attr.max_atk += Math.ceil(attr.max_atk * tech_add_atk / 100);
};
